package edu.hrbeu.crc.interceptor;


import edu.hrbeu.crc.context.BaseContext;
import edu.hrbeu.crc.common.utils.JwtUtil;
import edu.hrbeu.crc.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * JWT令牌校验拦截器
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    private static final String USER_ID = "id";

    /**
     * 校验 JWT 令牌
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前拦截到的是否是 Controller 方法（非静态资源）
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 1. 从请求头中获取令牌（与原逻辑一致）
        String token = request.getHeader(jwtProperties.getUserTokenName());

        // 2. 校验令牌（与原逻辑一致）
        try {
            log.info("JWT 校验开始: {}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Integer userId = Integer.valueOf(claims.get(USER_ID).toString());
            log.info("当前用户 ID: {}", userId);
            BaseContext.setCurrentId(userId);
            return true;
        } catch (Exception ex) {
            // 校验失败时返回 401 状态码
//            log.info("被拦截了捏");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 显式使用状态码常量
            return false;
        }
    }
}
